package com.zq.assistant.utils;

import java.io.Reader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

public class JsonUtils {

	private static final Gson gson;

    static {

        gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

    public static Gson getGson(){

        return gson;
    }
    
    public static <T,G> T toObject(String jsonString,Class<T> mainClass,Class<G> genericClass){
    	
    	if(genericClass == null){
    		return gson.fromJson(jsonString, mainClass);
    	}
    	return gson.fromJson(jsonString, type(mainClass,genericClass));
    }

    public static <T,G> T toObject(String jsonString,Class<T> mainClass){
    	
    	return gson.fromJson(jsonString, mainClass);
    }

    public static <T,G> T toObject(Reader reader, Class<T> mainClass, Class<G> genericClass){

        if(genericClass == null){
            return gson.fromJson(reader, mainClass);
        }

        return gson.fromJson(reader, type(mainClass,genericClass));
    }
    
    public static String toJsonString(Object object){
    	
    	return gson.toJson(object);
    }
    
    private static ParameterizedType type(final Class<?> rawClass, final Type...types){

        return new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return types;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }

            @Override
            public Type getRawType() {
                return rawClass;
            }
        };
    }
}
